import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import { ref } from 'vue'
import { getToken } from '@/utils/auth'
import { useStore } from 'vuex'
import type { ChatMessage } from '@/types/chat'

export function useWebSocket() {
  const client = ref<Client | null>(null)
  const connected = ref(false)
  const store = useStore()
  const messageHandlers = ref<((message: any) => void)[]>([])
  const messageMap = new Map<number, any>()
  const messageConfirmHandlers = ref<((messageId: number) => void)[]>([])
  let reconnectInterval: number | null = null;


  const addMessageHandler = (handler: (message: any) => void) => {
    messageHandlers.value.push(handler)
  }

  const addConfirmHandler = (handler: (messageId: number) => void) => {
    messageConfirmHandlers.value.push(handler)
  }

  const connect = () => {
    // 清除之前的重连定时器
    if (reconnectInterval) {
      clearInterval(reconnectInterval)
    }

    const token = getToken()
    if (!token) {
      console.error('No token found')
      return
    }

    if (!store.state.user.id) {
      console.error('未找到用户ID，取消连接')
      return
    }

    console.log('开始WebSocket连接，用户ID:', store.state.user.id)
    
    // 如果已经有连接，先断开
    if (client.value?.connected) {
      console.log('断开现有连接')
      client.value.deactivate()
    }
    
    initWebSocket()
    
    // 添加重连逻辑
    reconnectInterval = window.setInterval(() => {
      if (!client.value?.connected) {
        console.log('检测到连接断开，尝试重新连接...')
        initWebSocket()
      }
    }, 30000)
  }

  // 初始化WebSocket连接
  const initWebSocket = () => {
    // 如果用户ID不存在，则打印错误信息并返回
    if (!store.state.user.id) {
      console.error('initWebSocket: 用户ID不存在')
      return
    }

    // 获取token
    const token = getToken()
    // 如果token不存在，则打印错误信息并返回
    if (!token) {
      console.error('未找到有效的token')
      return
    }

    try {
      // 创建WebSocket客户端
      client.value = new Client({
        webSocketFactory: () => {
          // 创建SockJS连接
          const socket = new SockJS(`http://localhost:8080/ws?token=${encodeURIComponent(token || '')}`)
          return socket
        },
        connectHeaders: {
          // 添加Authorization头
          Authorization: `Bearer ${getToken()}`  // 确保添加 Bearer 前缀
        },
        // 添加调试日志
        debug: function (str) {
          // 在这里检查 RECEIPT 和 CONNECTED
          if (str.includes('RECEIPT')) {
            console.log('收到 RECEIPT 消息');
          }
          if (str.includes('CONNECTED')) {
            console.log('收到 CONNECTED 消息');
            connected.value = true;
          }
        },
        // 启用心跳检测，增加心跳间隔
        heartbeatIncoming: 5000,
        heartbeatOutgoing: 5000,
        // 重连配置
        reconnectDelay: 5000,
        maxWebSocketChunkSize: 8192,
        onConnect: (frame) => {
          console.log('WebSocket连接成功，frame:', frame)
          connected.value = true
          // 确保在连接成功后再初始化订阅
          setTimeout(() => {
            initSubscriptions()
          }, 1000)
        },
        onDisconnect: () => {
          console.log('WebSocket断开连接')
          connected.value = false
        },
        onStompError: (frame) => {
          console.error('STOMP错误:', frame)
          console.error('错误详情:', frame.body)
          connected.value = false
          // 发生错误时延迟重新连接
          if (client.value) {
            console.log('发生错误，5秒后尝试重新连接...')
            setTimeout(() => {
              if (!connected.value) {
                client.value?.activate()
              }
            }, 5000)
          }
        },
        // 增加连接超时时间
        connectionTimeout: 30000
      })

      console.log('正在激活WebSocket连接...')
      client.value.activate()
      
    } catch (error) {
      console.error('WebSocket初始化失败:', error)
      connected.value = false
    }
  }

  const sendMessage = async (message: any) => {
    // 添加重试机制
    let retries = 0
    const maxRetries = 3
    
    while (retries < maxRetries) {
      if (client.value?.connected && connected.value) {
        try {
          console.log('准备发送WebSocket消息:', message)
          
          // 创建本地消息对象
          const localMessage: ChatMessage = {
            ...message,
            id: Date.now(),
            senderId: store.state.user.id,
            receiverId: message.receiverId,
            time: new Date().toISOString(),
            status: 'SENDING',
            isSelf: true,
            type: message.type || 'text',
            appointmentId: message.appointmentId
          }
          
          messageMap.set(localMessage.id, localMessage)
          messageHandlers.value.forEach(handler => handler(localMessage))
          
          await new Promise((resolve, reject) => {
            try {
              client.value!.publish({
                destination: '/app/chat.send',
                body: JSON.stringify(localMessage),
                headers: {
                  'content-type': 'application/json'
                }
              })
              resolve(localMessage)
            } catch (error) {
              reject(error)
            }
          })
          
          return localMessage
          
        } catch (error) {
          console.error(`发送消息失败(重试 ${retries + 1}/${maxRetries}):`, error)
          retries++
          if (retries === maxRetries) {
            throw error
          }
          // 等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000))
        }
      } else {
        console.log('WebSocket未连接，等待连接...')
        await new Promise(resolve => setTimeout(resolve, 1000))
        retries++
        if (retries === maxRetries) {
          throw new Error('WebSocket连接超时')
        }
      }
    }
  }

  // 初始化时订阅消息通道
  const initSubscriptions = () => {
    if (client.value?.connected) {
      const userId = store.state.user.id
      if (!userId) {
        console.error('用户信息不完整，无法订阅消息', { userId })
        return
      }

      console.log('开始订阅消息，用户ID:', userId)
      
      // 订阅个人消息
      client.value.subscribe(`/user/queue/messages`, (message) => {
        console.log('WebSocket - 订阅ID:', message.headers.subscription)
        console.log('WebSocket - 当前用户ID:', store.state.user.id)
        console.log('WebSocket - 消息目标:', message.headers.destination)
        
        try {
          const data = JSON.parse(message.body)
          console.log('WebSocket - 解析后的消息:', data)
          
          // 检查消息是否已经存在，避免重复显示
          const existingMessage = messageMap.get(data.id)
          if (existingMessage) {
            console.log('消息已存在，更新状态')
            messageHandlers.value.forEach(handler => handler({
              ...existingMessage,
              status: 'DELIVERED'
            }))
            return
          }
          
          // 处理新收到的消息
          messageHandlers.value.forEach(handler => handler({
            ...data,
            status: 'DELIVERED',
            isSelf: data.senderId === store.state.user.id
          }))
        } catch (error) {
          console.error('WebSocket - 消息处理异常:', error)
        }
      })

      // 订阅确认消息
      client.value.subscribe(`/user/queue/ack`, (message) => {
        try {
          const data = JSON.parse(message.body)
          console.log('收到确认消息:', data)
          
          // 通知消息确认处理器
          messageConfirmHandlers.value.forEach(handler => handler(data.messageId))
          
          // 清理消息映射
          messageMap.delete(data.messageId)
        } catch (error) {
          console.error('处理确认消息失败:', error)
        }
      })

      console.log('WebSocket订阅完成，等待消息...')
    } else {
      console.warn('WebSocket订阅失败：未连接')
      console.warn('连接状态:', client.value?.connected)
    }
  }

  return {
    connect,
    sendMessage,
    connected,
    addMessageHandler,
    addConfirmHandler
  }
} 